package cxm.mmp.aud;

import java.util.concurrent.ArrayBlockingQueue;

import cxm.lib.util.MyLog;

// this class is used to keep a cache from sender
// then reader can grab data as necessary
public class RecordingDataAdaper {
	ArrayBlockingQueue<Byte> dataList = null;
	
	public RecordingDataAdaper() {
		// create 64kb buffera
		this.dataList = new ArrayBlockingQueue<Byte>(1024 * 64);
	}

	public int setData(byte[] data, int start, int num) {
		// add to buffer list
		int i = 0;
		synchronized (this.dataList) {
			for (i = 0; i < num; i++)
				try {
					this.dataList.put(data[start + i]);
				} catch (Exception e) {
					MyLog.Log(MyLog.Level.Error, "Cannot put data into buffer");
					break;
				}
		}

		return i;
	}
	
	public int getData(byte[] data, int start, int num) {
		if (this.dataList.size() == 0)
			return 0;

		// copy num data
		int i = 0;
		synchronized (this.dataList) {
			for (i = 0; i < num && !this.dataList.isEmpty(); i++)
				data[start + i] = this.dataList.poll();
		}
		
		return i;
	}
}
